package com.gu.controller;

import Utils.RandomProducer;
import com.gu.service.MessageSenderService;
import entity.CommonResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.omg.CORBA.TIMEOUT;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * Description:
 *
 * @Autor: Rolin
 * datetime: 06-08-22:13
 */
@RestController
@Api(tags = "短信服务管理")
@CrossOrigin
@RequestMapping("/edu/message")
public class MessageSenderController {

    @Resource
    private MessageSenderService messageSenderService;
    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    @ApiOperation("短信发送")
    @GetMapping("/sender/{phoneNum}")
    public CommonResult messageSender(@PathVariable("phoneNum")String phoneNum){
        //判断redis中的验证码是否过期：
        String message_code = (String) redisTemplate.opsForValue().get(phoneNum);
        if(!StringUtils.isEmpty(message_code)){
            System.out.println(message_code);
            return CommonResult.success().data("code",message_code);
        }
        //redis短信过期后：
        Map<String, Object> randomMap = RandomProducer.produceFourBitRandom();
        boolean result = messageSenderService.send(phoneNum, "SMS_154950909",randomMap);
        if (result){
            redisTemplate.opsForValue().set(phoneNum,randomMap.get("code"),2,TimeUnit.MINUTES);
            return CommonResult.success().data("code",randomMap.get("code"));
        }else {
            return CommonResult.error().message("验证码短信发送失败");      }
    }
}
